/*
 * Copyright (C) 冷锋
 */
#ifndef SERVER_H
#define SERVER_H
#include "epollsvrio.h"
#include "tool/minheap.h"
#include "tool/timeevent.h"

class CLogicThread;
class CLogicHandler;

typedef struct tagTimer
{
	unsigned int timeout;
}Timer;

class CServer:public CEpollSvrIO
{
public:
	CServer(char*sIP,const short iPort);
protected:
	int  OnConnect( int fd,sockaddr* );
	int  OnClose( Connection*pConn );
	int  OnRead( Connection*pConn );
	int  OnWrite( Connection*pConn );

	int  GetPackHeaderLen(){ return sizeof(Packet); }
	int  CloseConnection( Connection* );
	int  ReadOnePack(Connection* );//读取第一个包,此包可能是一个完整包的后半部分

	int  EnQueue(const std::list<HandleBuffer*>&,Connection*pConn);//往待处理队列添加数据包
	int  Send( HandleBuffer*result );

	//逻辑线程中处理
	virtual int  Handle( HandleBuffer*buf );//子类重写Handle函数进行逻辑处理	
	int ProcessTimeOut();//返回
	int OnTimer(CTimeEvent*);
public:
	int		LogicLoop();
	int		Loop();
	void	Exit();
	//以毫秒为单位
	int		DelayCall( int timeout,cbTimeOut cbfunc, void*arg);

private:
	ConnectionMgr*				m_pConnMgr;

	std::list<HandleBuffer*>	m_RecvQueue;//接收队列
	CThMutex					m_RecvLock;
	CThMutex					m_SendLock;
	CThCond						m_HaveWorkConn;
	CLogicThread*				m_pLogicThread;//逻辑线程
	CLogicHandler*				m_pLogicHandler;

	CMinHeap<CTimeEvent>*		m_pTimeOutHeap;	

	bool						m_bExit;

	friend class CLogicHandler;

};

class CLogicThread:public CThread
{
public:
	CLogicThread( CServer*p );
private:
	void Run();
private:
	CServer*m_pIO;
};
#endif
